/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/24 17:07
 */
package org.mechanic.fund.repository.product.impl;

import org.apache.commons.lang3.StringUtils;
import org.mechanic.fund.domain.product.Product;
import org.mechanic.fund.domain.product.ProductStyle;
import org.mechanic.fund.repository.product.ProductRepositoryCustom;
import org.mechanic.utils.collection.ListUtil;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * 产品JPA自定义实现
 *
 * @author mechanic
 * @version 0.0.1
 */
public class ProductRepositoryImpl implements ProductRepositoryCustom {

    @PersistenceContext
    private EntityManager em;

    public ProductRepositoryImpl() {
    }

    /**
     * 返回模糊匹配产品名称、产品代码和完全匹配产品风格类型的产品信息列表
     * @param name 名称
     * @param code 产品代码
     * @param style 产品风格类型
     * @return 产品信息列表
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<Product> findProductListOrderByCreateTimeAsc(
      String name, String code, ProductStyle style) {
        List<Product> list = ListUtil.emptyList();

        name = StringUtils.isBlank(name) ? "%" : "%" + name + "%";
        code = StringUtils.isBlank(code) ? "%" : "%" + code + "%";

        String sqlString = "SELECT t FROM Product t WHERE t.name LIKE ?1 AND t.code LIKE ?2 ";

        Query query = null;

        if (style != null && StringUtils.isNotBlank(style.getId())) {
            query = em.createQuery(sqlString + " AND t.productStyle = ?3 ORDER BY t.createTime ASC ")
                      .setParameter(1, name)
                      .setParameter(2, code )
                      .setParameter(3, style);
        } else {
            query = em.createQuery(sqlString + " ORDER BY t.createTime ASC ")
                      .setParameter(1, name)
                      .setParameter(2, code);
        }
        return (List<Product>) query.getResultList();
    }
}
